package com.ysu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysu.demo.dataobject.College;
import com.ysu.demo.dto.UserDTOToken;
import com.ysu.demo.enums.ExceptionEnum;
import com.ysu.demo.exception.BaseException;
import com.ysu.demo.from.LoginFrom;
import com.ysu.demo.service.ICollegeService;
import com.ysu.demo.service.LoginService;
import com.ysu.demo.utlis.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author ：lhw
 * @date ：Created in 2019/9/8 10:24
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    ICollegeService collegeService;

    @Value("${admins.user}")
    private String user;

    @Value("${admins.password}")
    private String password;

    @Override
    public UserDTOToken login(LoginFrom loginFrom) throws Throwable {
        UserDTOToken userDTOToken = new UserDTOToken();

        if(loginFrom.getLogin().equals(user) && loginFrom.getPassword().equals(password)){
            userDTOToken.setPower(2); // 管理员
            userDTOToken.setToken(TokenUtil.getToken()); // UUID

            stringRedisTemplate.opsForValue().set(
                    userDTOToken.getToken(),
                    objectMapper.writeValueAsString(userDTOToken),
                    7200,
                    TimeUnit.SECONDS
                );
        }
        else {
            College college = collegeService.getOne(new QueryWrapper<College>().eq("login",loginFrom.getLogin()));

            if(college == null || !college.getPassword().equals(loginFrom.getPassword())){
                throw  new BaseException(ExceptionEnum.NOT_FIND);
            }

            userDTOToken.setPower(1); // 普通用户
            userDTOToken.setToken(TokenUtil.getToken());
            userDTOToken.setCollege(college);

            stringRedisTemplate.opsForValue().set(
                    userDTOToken.getToken(),
                    objectMapper.writeValueAsString(userDTOToken),
                    7200,
                    TimeUnit.SECONDS
            );
        }

        return userDTOToken;
    }
}
